package com.intercepter;

import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


/**
 * SpringMVC拦截器
 *
 * Created by Administrator on 2018-8-18 0018.
 */
public class LoginHandlerIntercepter implements HandlerInterceptor {

    private List<String> exceptUrls;

    public List<String> getExceptUrls() {
        return exceptUrls;
    }

    public void setExceptUrls(List<String> exceptUrls) {
        this.exceptUrls = exceptUrls;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        String requestURI = request.getRequestURI();
        HttpSession session = request.getSession();
        for (String url : exceptUrls) {
            if(url.endsWith("/**")){
                if (requestURI.startsWith(url.substring(0, url.length() - 3))) {
                    return true;
                }
            } else if (requestURI.startsWith(url)) {
                return true;
            }
        }
        if (requestURI.indexOf("home/login") != -1) {
            String user = (String) session.getAttribute("username");
            if (user != null) {
                return true;
            } else {
                return false;
            }
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
